package me.flyray.biz.thymeleaf.modules.goods.rest;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.biz.common.msg.BizResponseCode;
import com.github.wxiaoqi.security.biz.common.qr.request.QrGoodsRequestParam;
import com.github.wxiaoqi.security.biz.common.qr.request.QrQueryGoodsParam;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.ResponseHelper;
import com.github.wxiaoqi.security.common.util.ZipHelper;
import com.google.zxing.WriterException;

import me.flyray.biz.thymeleaf.modules.goods.biz.QrGoodsInfoBiz;
import me.flyray.biz.thymeleaf.modules.goods.entity.QrGoodsInfo;


/**
 * 商品
 * @author Administrator
 *
 */
@Controller
@RequestMapping("qrGoodsInfos")
public class QrGoodsInfoController extends BaseController<QrGoodsInfoBiz, QrGoodsInfo>  {

	private static final Logger logger = LoggerFactory.getLogger(QrGoodsInfoController.class);


	/**
	 * 查询商品列表
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/list", method=RequestMethod.POST)
	public TableResultResponse<QrGoodsInfo> query(@RequestBody QrQueryGoodsParam param) {
		logger.info("查询商品列表。。。{}"+param);
		return baseBiz.queryList(param);
	}


	/**
	 * 添加
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public Map<String, Object> add(@RequestBody QrGoodsRequestParam param) {
		logger.info("添加商品。。。{}"+param);
		QrGoodsInfo goodsInfo = baseBiz.addGoodsInfo(param);
		if (goodsInfo == null) {
			return ResponseHelper.success(null, null, BizResponseCode.OK.getCode(), BizResponseCode.OK.getMessage());
		}else {
			return ResponseHelper.success(null, null, BizResponseCode.FUNCTION_EXIST.getCode(), BizResponseCode.FUNCTION_EXIST.getMessage());
		}
	}

	/**
	 * 导入
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/import", method=RequestMethod.POST)
	public Map<String, Object> importData(@RequestBody Map<String, Object> param) {
		logger.info("添加商品。。。{}"+param);
		baseBiz.importGoodsList(param);
		return ResponseHelper.success(null, null, BizResponseCode.OK.getCode(), BizResponseCode.OK.getMessage());
	}

	/**
	 * 修改
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public Map<String, Object> update(@RequestBody QrGoodsRequestParam param) {
		logger.info("修改商品。。。{}"+param);
		QrGoodsInfo goodsInfo = baseBiz.updateGoodsInfo(param);
		if (goodsInfo != null) {
			return ResponseHelper.success(null, null, BizResponseCode.OK.getCode(), BizResponseCode.OK.getMessage());
		}else {
			return ResponseHelper.success(null, null, BizResponseCode.FUNCTION_EXIST.getCode(), BizResponseCode.FUNCTION_EXIST.getMessage());
		}
	}


	/**
	 * 删除
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	public Map<String, Object> delete(@RequestBody QrGoodsRequestParam param) {
		logger.info("删除商品。。。{}"+param);
		QrGoodsInfo goodsInfo = baseBiz.deleteGoodsInfo(param);
		if (goodsInfo != null) {
			return ResponseHelper.success(null, null, BizResponseCode.OK.getCode(), BizResponseCode.OK.getMessage());
		}else {
			return ResponseHelper.success(null, null, BizResponseCode.FUNCTION_EXIST.getCode(), BizResponseCode.FUNCTION_EXIST.getMessage());
		}
	}


	/**
	 * 生成二维码
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/createQr", method=RequestMethod.POST)
	public Map<String, Object> createQr(@RequestBody Map<String, Object> param) {
		logger.info("生成二维码参数。。。{}"+param);
		Map<String, Object> res = new HashMap<>();
		//		if (res != null) {
		//			return ResponseHelper.success(res, null, BizResponseCode.OK.getCode(), BizResponseCode.OK.getMessage());
		//		}else {
		//			return ResponseHelper.success(null, null, BizResponseCode.ABNORMAL_FIELDS.getCode(), BizResponseCode.ABNORMAL_FIELDS.getMessage());
		//		}
		return res;
	}

	@ResponseBody
	@RequestMapping(value="/downloadZipQr", method=RequestMethod.POST)
	public Map<String, Object> downloadZipQr(HttpServletRequest request, HttpServletResponse response) throws IOException, WriterException {
		String idString= null; 
		try {
			BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
			StringBuilder responseStrBuilder = new StringBuilder();
			String inputStr;
			while ((inputStr = streamReader.readLine()) != null){
				responseStrBuilder.append(inputStr);
			}

			JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
			idString =  (String)jsonObject.get("idStr");
			logger.info("下载二维码。。。。{}"+ idString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String realPath = "/opt/app/dist/"; 

		//1 生成二维码 
		String projectName = "goodQr"; 
		String path = realPath + projectName; 
		
		File file = new File(path); 

		logger.info("生成文件夹。。。。");
		file.mkdirs(); 
		
		baseBiz.createGoodsQr(idString, path);

		//2 生成zip文件 
		ZipHelper.zipCompress(path, path + ".zip"); 
		
		//删除文件夹
		deleteDir(file);

		Map<String, Object> res = new HashMap<>();
		res.put("code", "0000");
		return res;
	}
	
	private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

}

